package com.sy.server.impl;


import com.sy.config.SystemConfig;
import com.sy.dao.OsslogDao;
import com.sy.entity.Osslog;
import com.sy.server.intf.OsslogService;
import com.sy.util.DateUtil;
import com.sy.util.StrUtil;
import com.sy.utils.AliOssUtil;
import com.sy.utils.BaidCensorUtil;
import com.sy.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


@Service
public class OsslogServiceImpl implements OsslogService {

    @Autowired
    private OsslogDao osslogDao;

    private final String bname="suyiBetter";

    @Override
    public R save(Osslog osslog) {
        if (osslogDao.insert(osslog) > 0) {
            return R.ok();
        } else {
            return R.fail("新增失败");
        }
    }

    @Override
    public R delById(int id) {
        if (osslogDao.deleteById(id) > 0) {
            return R.ok();
        } else {
            return R.fail("删除失败");
        }
    }

    @Override
    public R all() {
        return R.ok(osslogDao.all());
    }

    @Override
    public R upload(MultipartFile file) {
        //1.校验参数是否正确
        if (!file.isEmpty()) {
            try {
                //2.将文件转换为数据流
                byte[] data = file.getBytes();
                //3.图片合法性判断
                if (BaidCensorUtil.consorImg(data)) {
                    //4.对文件名进行重命名，防止重名和名字不合法
                    String fileName = file.getName();
                    fileName = rename(fileName);
                    //5.进行文件上传，并返回URL，用于日志记录
                    String url = AliOssUtil.upload(bname, fileName, SystemConfig.PIC_URLTIME, data);
                    if (StrUtil.checkNoEmpty(url)) {
                        //记录到oss日志中
                        osslogDao.insert(new Osslog(fileName, bname, url, 1, DateUtil.addTime(SystemConfig.PIC_URLTIME, 3)));
                        //6.上传成功，返回URL
                        return R.ok(url);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.fail();
    }

    //重命名
    private String rename(String fileName) {
        //判断长度是否合法
        if (fileName.length() > 30) {
            fileName = fileName.substring(fileName.length() - 30);
        }
        //返回值，反正重名
        return System.currentTimeMillis() + fileName;
    }
}
